import http from './request';

/**
 * 登录
 * @param {Object} data 登录信息
 * @returns {Promise}
 */
export const login = (data) => {
  return new Promise((resolve, reject) => {
    http.post('/auth/login', data)
      .then(res => {
        // 存储token
        uni.setStorageSync('token', res.token);
        // 存储用户信息
        uni.setStorageSync('userInfo', res.user);
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
};

/**
 * 注册
 * @param {Object} data 注册信息
 * @returns {Promise}
 */
export const register = (data) => {
  return http.post('/auth/register', data);
};

/**
 * 退出登录
 * @returns {Promise}
 */
export const logout = () => {
  return new Promise((resolve) => {
    // 清除token
    uni.removeStorageSync('token');
    // 清除用户信息
    uni.removeStorageSync('userInfo');
    // 跳转到登录页
    uni.navigateTo({
      url: '/pages/login/login'
    });
    resolve();
  });
};

/**
 * 获取用户信息
 * @returns {Promise}
 */
export const getUserInfo = () => {
  return new Promise((resolve) => {
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      resolve(userInfo);
    } else {
      http.get('/user/info')
        .then(res => {
          // 存储用户信息
          uni.setStorageSync('userInfo', res.data);
          resolve(res.data);
        })
        .catch(() => {
          resolve(null);
        });
    }
  });
};

/**
 * 验证token是否有效
 * @returns {Promise}
 */
export const validateToken = () => {
  return http.get('/auth/validate');
};

/**
 * 更新用户信息
 * @param {Object} data 用户信息
 * @returns {Promise}
 */
export const updateUserInfo = (data) => {
  return new Promise((resolve, reject) => {
    http.put('/user/info', data)
      .then(res => {
        // 更新本地存储的用户信息
        const userInfo = uni.getStorageSync('userInfo');
        uni.setStorageSync('userInfo', { ...userInfo, ...data });
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
};